package com.lungle.warmdiary.app.view.me;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.AppManager;
import com.lungle.warmdiary.app.api.exception.ApiErrorHelper;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.content.db.DAOFactory;
import com.lungle.warmdiary.app.content.db.MediaAccountDAO;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.UserChangeEvent;
import com.lungle.warmdiary.app.model.request.LoginPost;
import com.lungle.warmdiary.app.model.response.MediaAccount;
import com.lungle.warmdiary.app.model.response.Token;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.ui.InputItemView;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.MainActivity;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String LOGIN_SCREEN = "login screen";

    protected static final String TAG = LoginActivity.class.getSimpleName();

    public static final int REQUEST_CODE_INIT = 0;
    public static final int REQUEST_CODE_RELOGIN = 1;

    public static final String BUNDLE_KEY_REQUEST_CODE = "BUNDLE_KEY_REQUEST_CODE";


    private InputItemView mEtUserName;
    private InputItemView mEtPassword;
    private Button mBtnLogin;
    private int requestCode = REQUEST_CODE_INIT;
    private String mUserName, mPassword;

    private TextView mTvChangePwd;


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(LOGIN_SCREEN);
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(LOGIN_SCREEN);
        MobclickAgent.onPause(this);

    }

    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void onBackPressed() {
        if (requestCode == REQUEST_CODE_RELOGIN) {
            finish();
            AppManager.getAppManager().AppExit(this);
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected boolean hasActionBar() {
        return true;
    }

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    protected int getActionBarTitle() {
        return R.string.login;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        Intent data = getIntent();
        if (data != null) {
            requestCode = data.getIntExtra(BUNDLE_KEY_REQUEST_CODE,
                    REQUEST_CODE_INIT);
        }
        initView();
    }


    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.btn_login) {
            handleLogin();
        } else if (id == R.id.tv_pwd_change) {
            UIHelper.showChangePwd(this);
        }
    }


    private void handleLogin() {
        if (!prepareForLogin()) {
            return;
        }
        mUserName = mEtUserName.getInputText();
        mPassword = mEtPassword.getInputText();

        LoginPost loginReq = new LoginPost(mUserName, mPassword);
        loginReq.setMac(TDevice.getMAC(LoginActivity.this));
        loginReq.setMac(TDevice.getDeviceId(LoginActivity.this));
        showWaitDialog();

        ApiFactory.getBaseApi().login(loginReq).flatMap(tokenResult -> {
            if (tokenResult.isOk()) {
                Token data = tokenResult.getData();
                String token = data.getToken();
                AppContext.getInstance().setToken(token);
                AppContext.getInstance().setLoginUid(data.getUserid());
                loadMediaAccountList();
                return ApiFactory.getUserApi().getUserProfile();
            } else {
                return Observable.error(new ApiException(tokenResult.getCode(), tokenResult.getMsg()));
            }
        }).compose(resultObservable -> resultObservable).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<User>>(this) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                        AppContext.shouldShowReloadin = true;

                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);

                        finish();
                    }

                    @Override
                    public void onNext(Result<User> userResult) {
                        AppContext.getInstance().saveLoginInfo(userResult.getData());
                        EventBus.getDefault().post(new UserChangeEvent(userResult.getData().getUsername()));

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        if (e instanceof ApiException) {
                            ApiException exception = (ApiException) e;
                            if (exception.isTokenExpried()) {
                                AppContext.showToastShort("用户已在其他设备上登录");
                            } else if (exception.isInvlidClient()) {
                                AppContext.showToastShort("非法客户端");
                            } else {
                                ApiErrorHelper.showErrorDetail(exception.getExtendErrorMsg());
                            }

                        } else {
                            AppContext.showToastShort("服务暂不可用");
                        }
                        AppContext.getInstance().Logout();
                    }
                });

    }

    private boolean prepareForLogin() {
        if (!TDevice.hasInternet()) {
            AppContext.showToastShort(R.string.tip_no_internet);
            return false;
        }
        String uName = mEtUserName.getInputText();
        if (TextUtils.isEmpty(uName)) {
            AppContext.showToastShort(R.string.tip_please_input_username);
            mEtUserName.requestFocus();
            return false;
        }
        String pwd = mEtPassword.getInputText();
        if (TextUtils.isEmpty(pwd)) {
            AppContext.showToastShort(R.string.tip_please_input_password);
            mEtPassword.requestFocus();
            return false;
        }
        return true;
    }

    private void handleLoginSuccess() {
        Intent data = new Intent();
        data.putExtra(BUNDLE_KEY_REQUEST_CODE, requestCode);
        setResult(RESULT_OK, data);
        finish();
    }


    @Override
    public void initView() {
        mEtUserName = (InputItemView) findViewById(R.id.et_username);
        mEtPassword = (InputItemView) findViewById(R.id.et_account);
        mTvChangePwd = (TextView) findViewById(R.id.tv_pwd_change);
        mTvChangePwd.setOnClickListener(this);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mBtnLogin.setOnClickListener(this);
    }

    @Override
    public void initData() {

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.login_menu, menu);
        menu.findItem(R.id.login_menu_register);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);

        return true;
    }


    private void loadMediaAccountList() {
        LogUtils.printLogD("loadMediaAccountList");
        ApiFactory.getUserApi().getMediaAccountList(1)
                .subscribeOn(Schedulers.newThread())
                .subscribe(new BaseSubscriber<Result<List<MediaAccount>>>(this) {
                    @Override
                    public void onNext(Result<List<MediaAccount>> listResult) {
                        List<MediaAccount> data = listResult.getData();
                        if (data != null && !data.isEmpty()) {
                            AppContext.setMeidaAccount(true);
                        } else {
                            AppContext.setMeidaAccount(false);
                        }
                        MediaAccountDAO mediaAccountDAO = DAOFactory.getMediaAccountDAO();
                        mediaAccountDAO.insert(data);
                        mediaAccountDAO.close();
                    }
                });

    }


}
